package com.iqik.ioc.dao.impl;

import com.iqik.ioc.anno.Autowired;
import com.iqik.ioc.anno.Service;
import com.iqik.ioc.dao.AccountDao;
import com.iqik.ioc.pojo.Account;
import com.iqik.ioc.utils.ConnectionUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Service
public class AccountDaoImpl implements AccountDao {

    @Autowired
    private ConnectionUtils connectionUtils;

    @Override
    public Account getAccountByCode(int code) throws SQLException {
        Connection conn = connectionUtils.getCurrentThreadConn();
        String sql = "select * from account where code = ?";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setInt(1, code);
        ResultSet resultSet = preparedStatement.executeQuery();
        Account account = new Account();
        while (resultSet.next()) {
            account.setCode(resultSet.getInt("code"));
            account.setMoney(resultSet.getFloat("money"));
            account.setName(resultSet.getString("name"));
        }
        System.out.println(account);
        resultSet.close();
        preparedStatement.close();
        return account;
    }

    @Override
    public int updateAccountByCode(Account account) throws Exception {
        Connection conn = connectionUtils.getCurrentThreadConn();
        String sql = "update account set money=? where code=?";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setFloat(1, account.getMoney());
        preparedStatement.setInt(2, account.getCode());
        int i = preparedStatement.executeUpdate();
        return i;
    }
}
